<!--
 * @Author: wuzhen
 * @Date: 2019-12-03 14:04:35
 * @LastEditors: wuzhen
 * @LastEditTime: 2019-12-06 09:18:00
 * @Description: 视频上传
 -->

<template>
  <div class="upload">
    <div class="upload-list" v-for="(item, index) in uploadList" :key="index" :style="styleProps">
      <img :src="'https://res.squrab.com/' + item.gif">
      <div class="upload-list-cover">
        <Icon type="ios-play" @click.native="handleView(item)"></Icon>
        <Icon type="ios-trash-outline" @click.native="handleRemove(item)"></Icon>
      </div>
    </div>
    <div class="upload-list" v-if="showProgress" :style="styleProps">
      <Progress :percent="percentage" hide-info></Progress>
    </div>
    <Upload ref="upload" :format="['mp4']" :show-upload-list="false" accept="video/*" :max-size="5 * 1024" :before-upload="handleBeforeUpload" :on-success="handleSuccess" :on-exceeded-size="handleMaxSize" action="https://upload.qiniup.com" :data="uploadData" type="drag" style="display:inline-block;margin-right:15px">
      <div :style="styleProps" class="upload-action">
        <Icon type="ios-add" size="40"></Icon>
        <p>视频上传</p>
      </div>
    </Upload>
    <Upload ref="uploadGif" :format="['gif']" accept="image/*" action="https://upload.qiniup.com" :data="uploadGif" :show-upload-list="false" :on-success="handleSuccessGif" style="display:inline-block;dispaly:none">
    </Upload>
    <Modal title="视频预览" v-model="showVideo" footer-hide>
      <!-- videoSrc -->
      <video :src="'https://res.squrab.com/' + videoSrc" v-if=" showVideo" autoplay controls style="width: 100%"></video>
    </Modal>
  </div>
</template>
<script>
import { inciseVideo, getQiniuToken } from "@/api";
export default {
  props: {
    // 默认显示文件
    defaultList: {
      type: Array,
      default: () => []
    },
    // 是否支持上传多个
    fileSize: {
      type: [Number, String],
      default: 5
    },
    maxSize: {
      type: Number,
      default: 2
    },
    format: {
      type: Array,
      default: () => ["jpg", "jpeg", "png", "bmp"]
    },
    accept: {
      type: String,
      default: "image/*"
    },
    // 图片框大小
    styleProps: {
      type: Object,
      default: () => {
        return {
          width: "100px",
          height: "100px"
        };
      }
    }
  },
  data() {
    return {
      uploadList: [],
      uploadData: {
        token: null,
        key: ""
      },
      uploadGif: {
        token: null,
        key: ""
      },
      videoObj: {
        mp4: "",
        gif: ""
      },
      showVideo: false,
      videoSrc: "",
      showProgress: false,
      percentage: 0
    };
  },
  mounted() {
    this.uploadList = this.defaultList;
  },
  methods: {
    async getToken() {
      const res = await getQiniuToken({ type: 1 });
      this.token = res.data.token;
    },
    // 文件上传前钩子-获取七牛云上传token
    handleBeforeUpload(file) {
      const url = URL.createObjectURL(file);
      const audioElement = new Audio(url);
      let duration;
      audioElement.addEventListener("loadedmetadata", async () => {
        try {
          duration = Math.floor(audioElement.duration); //时长为秒，小数，182.36
          this.getToken();
          await this.$Spin.show();
          const res = await inciseVideo({ video: file, length: duration });
          if (res.code !== 10000) {
            this.$Spin.hide();
            this.$Message.error(res.error);
            return;
          }
          await this.$Spin.hide();
          setTimeout(async () => {
            this.uploadGif = {
              token: this.token,
              key:
                "langya/image/gif/" +
                Math.ceil(Math.random() * Math.pow(10, 15)) +
                ".gif"
            };
            const gif = new File(
              [this.dataURLToBlob(res.data.gif_base64)],
              file.name.split(".")[0] + ".gif",
              { type: "image/gif" }
            );
            setTimeout(async () => {
              await this.$refs.uploadGif.post(gif);
            }, 100);
            this.uploadData = {
              token: this.token,
              key:
                "langya/video/mp4/" +
                Math.ceil(Math.random() * Math.pow(10, 15)) +
                ".mp4"
            };
            const video = new File(
              [this.dataURLToBlob(res.data.mp4_base64)],
              file.name.split(".")[0] + ".mp4",
              { type: "video/mp4" }
            );
            setTimeout(async () => {
              await this.$refs.upload.post(video);
            }, 100);
          }, 100);
        } catch (error) {
          throw error;
        }
      });
      return false;
    },
    dataURLToBlob(dataurl) {
      let arr = dataurl.split(",");
      let mime = arr[0].match(/:(.*?);/)[1];
      let bstr = atob(arr[1]);
      let n = bstr.length;
      let u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], { type: mime });
    },
    // gif上传成功
    handleSuccessGif(file) {
      this.videoObj.gif = file.key;
      const obj = { ...this.videoObj };
      this.uploadList = [obj];
      this.getFileList();
    },
    // 视频上传成功
    handleSuccess(file) {
      this.videoObj.mp4 = file.key;
      const obj = { ...this.videoObj };
      this.uploadList = [obj];
      this.getFileList();
    },
    // 上传进度钩子
    handleProgress(event) {
      this.showProgress = true;
      this.percentage = event.percent;
      if (event.percent === 100) {
        this.showProgress = false;
      }
    },
    handleMaxSize() {
      this.$Message.error(`文件太大，不能超过${this.maxSize}M`);
    },
    // 文件上传
    handleUpload() {
      this.$refs.upload.post(this.file);
    },
    // 图片预览
    handleView(file) {
      this.videoSrc = file.mp4;
      this.showVideo = true;
    },
    // 图片删除
    handleRemove(file) {
      this.uploadList.splice(this.uploadList.indexOf(file), 1);
      this.getFileList();
    },
    // 获取上传的文件
    getFileList() {
      this.$emit("file-list", this.uploadList);
    }
  }
};
</script>
<style lang="less" scoped>
.upload {
  &-list {
    display: inline-block;
    text-align: center;
    border: 1px solid transparent;
    border-radius: 4px;
    overflow: hidden;
    background: #fff;
    position: relative;
    box-shadow: 0 0px 2px rgba(0, 0, 0, 0.2);
    margin-right: 15px;
    img {
      width: 100%;
      height: 100%;
    }
    &-cover {
      display: none;
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      background: rgba(0, 0, 0, 0.6);
      align-items: center;
      justify-content: center;
      i {
        color: #fff;
        font-size: 20px;
        cursor: pointer;
        margin: 0 2px;
      }
    }
    &:hover {
      .upload-list-cover {
        display: flex;
      }
    }
  }
  &-action {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    p {
      font-size: 12px;
    }
  }
}
</style>